package xin.marcher.module.common.tair;

import lombok.Data;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * <p>
 */
@Data
@Configuration
@ConditionalOnProperty(prefix = "spring.tair", name = {"host", "password"})
public class TairConfig {

    @Value("${spring.tair.maxIdle:200}")
    private int maxIdle;

    @Value("${spring.tair.maxTotal:300}")
    private int maxTotal;

    @Value("${spring.tair.host}")
    private String host;

    @Value("${spring.tair.port:6379}")
    private int port;

    @Value("${spring.tair.password}")
    private String password;

    @Value("${spring.tair.timeout:3000}")
    private int timeout;

    @Bean
    @ConditionalOnClass(JedisPool.class)
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        // 最大空闲连接数，需自行评估，不超过Redis实例的最大连接数
        config.setMaxIdle(maxIdle);
        // 最大连接数，需自行评估，不超过Redis实例的最大连接数。
        config.setMaxTotal(maxTotal);
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);

        return new JedisPool(config, host, port, timeout, password);
    }

    @Bean
    @ConditionalOnClass(TairCache.class)
    public TairCache tairCache(JedisPool jedisPool) {
        return new TairCache(jedisPool);
    }

    @Bean
    @ConditionalOnClass(RedissonClient.class)
    public TairLock tairLock(TairCache tairCache) {
        return new TairLock(tairCache);
    }
}
